package com.thientan.service

import com.thientan.export.ExportHandlerImpl
import com.thientan.export.ExportRequest
import com.thientan.export.ExportType
import com.thientan.export.IExportParameterBuilder
import com.thientan.export.exceptions.ExportException

abstract class AbstractService implements IExportParameterBuilder{
	def exportData

	/**
	 * Return the widths of columns in the export file when export list of domains.
	 */
	protected Long[] getColWidth() {
		return []as Long[]
	}

	/**
	 * Return the column's headers in the export file when export list of domains.
	 */
	protected String[] getColTitles() {
		return []as String[]
	}

	/**
	 * Return the fields of domain to export.
	 */
	protected String[] getColNames() {
		return []as String[]
	}

	/**
	 * Return the type of columns when export list of domains.
	 */
	@SuppressWarnings("rawtypes")
	protected Class<?>[] getExportColType() {
		return [String.class, String.class]as Class<?>[]
	}
	
	def saveOrUpdate(object) {
		object.save()
	}

	/**
	 * Do export action.
	 * @param data MUST in format Map [variable1: value1, variable2 : value2, 'data' : List<the data list>]
	 * @param filename
	 * @param basePath
	 * @param type
	 * @param sheetNames
	 */
	public void export(def data, String filename, String basePath, ExportType type, String[] sheetNames, String resourcePath = null) throws ExportException {
		// Keep the exported data for the next using (apply parameters for exported file)
		this.setExportData(data)
		// Firstly: Prepare colTypes to export
		def colTypes = getExportColType()

		// Secondly : Prepare colNames , and this must match with properties in exported DTO
		def colNames = getColNames()
		// Prepare column titles which will be shown on EXCEL file exported.
		def colTitles = getColTitles()
		// The width of columns in excel file
		int[] colWidths = getColWidth()

		// Initialize export utility service
		ExportHandlerImpl exportHandlerImpl = new ExportHandlerImpl(exportTemplateFilePath : resourcePath, exportParameterBuilder : this)

		// Begin export parameters
		try {
			exportHandlerImpl.exportHandler(filename, basePath, type, data.data, colNames, colTypes,
					colTitles, colWidths, sheetNames)
		} catch (Exception e) {
			log.error (e.message)
			throw new ExportException("Unable to export data ", e)
		}
	}

	void prepareParametersBeforeExport(ExportRequest er){
		// Let sub-service to implement more.
	}

	void setExportData(def exportData){
		this.exportData = exportData
	}

	def getExportData(){
		this.exportData
	}
}
